package com.yudean.esb.service.impl;

import com.yudean.esb.service.handler.FWSDataHandler;
import com.yudean.esb.service.ErpClientService;
import com.yudean.esb.service.PutService;
import com.yudean.esb.service.handler.ReceiveDataService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import javax.annotation.Resource;
import javax.jws.WebService;
import java.io.UnsupportedEncodingException;

@WebService(endpointInterface = "com.yudean.esb.service.PutService", serviceName = "PutServiceService")
@Controller("soapPutServiceImpl")
@Scope("prototype")
public class PutServiceImpl implements PutService {

    private final static Logger log = LoggerFactory.getLogger(PutServiceImpl.class);
    @Resource
    private ReceiveDataService receiveDataServiceImpl;

    // 法务系统数据数据工具
    @Resource
    private FWSDataHandler fwsDataHandler;

    @Resource
    ErpClientService erpClientService;

    /**
     * 处理推送过来的数据
     *
     * @param serviceID     服务ID
     * @param token         安全验证码
     * @param transactionID 事务ID
     * @param pkg           当前包书
     * @param totalPackage  总共报数
     * @param rollback      是否回滚
     * @param data          数据内容
     * @return
     */
    @Override
    public String put(String serviceID, String token, String transactionID,
                      String pkg, String totalPackage, String rollback,
                      String forceReplace, String data) {
        // TODO: 这种判断非常耗时，待改进
        // 因为法务系统不愿意做调整的原因，只能为其做单独的

        try {
            erpClientService.addErpClientLog(token);
        } catch (Exception e) {
            log.error("save ERP log of /services/put error:", e);
        }
        try {
            data = java.net.URLDecoder.decode(data, "utf-8");
            log.info("转码后的：{}",data);
        } catch (UnsupportedEncodingException exception) {
            log.error("data URLDecode incorrect,don't need  URLDecode");
        }
        if ("erp_ids_payments".equals(serviceID)) {
            return fwsDataHandler.handlePaymentsData(data, token);
        } else if ("erp_ids_control".equals(serviceID)) {
            return fwsDataHandler.handleControlData(data, token);
        } else if ("erp_ids_contract".equals(serviceID)) {
            return fwsDataHandler.handleContractData(data, token);
        } else {
            return receiveDataServiceImpl.put(serviceID, token, transactionID, pkg, totalPackage, rollback, forceReplace, data);
        }
    }

}
